import React, { useState, useEffect } from 'react';
import { Form, Button, Modal, Upload } from 'antd';
import { UPLOAD_URL } from '../constants';
import { UploadOutlined } from '@ant-design/icons';
import { useImageModal } from '../store/hooks/useImageModal';
import { preview } from '../common/formData';
/**
 * @param {function} onSubmit 表单提交函数，会自动传入表单的值
 * @param {obj} formData 渲染表单所需的数据 见common文件夹下的formData.jsx文件
 * @returns
 */
const FormItem = ({
  onSubmit,
  formData,
  initialValues,
  defaultFileList = [],
  labels = ['submit', 'reset'],
  onReset = (form) => {
    form.resetFields();
  },
}) => {
  const { state, url, show, hide } = useImageModal();
  const [form] = Form.useForm();
  const onFinish = (values) => {
    if (onSubmit) {
      onSubmit(values);
    }
  };
  // 邪门方法
  useEffect(() => {
    form.resetFields();
  });
  return (
    <div className="form-container">
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
        onFinish={onFinish}
        initialValues={initialValues}
      >
        {formData.map((item, index) => (
          <Form.Item key={index} {...item}>
            {item.slot != 'upload' ? (
              item.slot
            ) : (
              <Upload
                name="file"
                action={UPLOAD_URL}
                listType="picture"
                className="upload-list-inline"
                maxCount="1"
                onPreview={preview}
                defaultFileList={defaultFileList}
              >
                <Button icon={<UploadOutlined />}>Upload</Button>
              </Upload>
            )}
          </Form.Item>
        ))}

        <Form.Item>
          <Button type="primary" htmlType="submit">
            {labels[0]}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button htmlType="button" onClick={() => onReset(form)}>
            {labels[1]}
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
export default FormItem;
